// CREATE TABLE `t_goods` (
//     `id` int(11) unsigned zerofill NOT NULL AUTO_INCREMENT,
//     `gid` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
//     `banner_imvs` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'banner图',
//     `goods_title` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '标题',
//     `goods_des` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '描述',
//     `unit_price` float(10,2) NOT NULL COMMENT '单价',
//     `detail_imvs` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '详情图',
//     `stock` int(10) NOT NULL DEFAULT '0' COMMENT '库存',
//     `place` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '产地',
//     `create_date` datetime DEFAULT NULL COMMENT '创建日期',
//     `update_date` datetime DEFAULT NULL COMMENT '修改日期',
//     PRIMARY KEY (`id`,`gid`) USING BTREE
//   ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci


let { v4: uuidv4 } = require("uuid")
const knex = require("../dao")
let TNAME = "t_goods";

class Goods {
    Add = (data, callback) => {
        data.gid = uuidv4()
        data.create_date = new Date()

        knex(TNAME).insert(data).then(res => {
            callback(undefined, { code: 0, msg: "添加成功", data: {} })
        }).catch(err => {
            callback(undefined, { code: 500, msg: err, data: {} })
        })
    }

    Del = ({ gid }, callback) => {
        knex(TNAME).where({ gid }).del().then(res => {
            callback(undefined, { code: 0, msg: "删除成功", data: {} })
        }).catch(err => {
            callback(undefined, { code: 500, msg: err, data: {} })
        })
    }

    Update = (data, callback) => {
        let { gid, create_date } = data
        data.create_date = new Date(create_date)
        data.update_date = new Date()
        knex(TNAME).where({ gid }).update(data).then(res => {
            callback(undefined, { code: 0, msg: "更新成功", data: {} })
        }).catch(err => {
            callback(undefined, { code: 500, msg: err, data: {} })
        })
    }

    List = ({ page, page_size }, callback) => {
        knex(TNAME).select().limit(page_size || 20).offset(page || 0).then(res => {
            callback(undefined, { code: 0, msg: "", data: res })
        }).catch(err => {
            callback(undefined, { code: 500, msg: err, data: {} })
        })
    }

    Detail = ({ gid }, callback) => {
        knex(TNAME).where({ gid }).select().then(res => {
            if (res.length == 0) {
                callback(undefined, { code: 0, msg: "", data: {} })
            } else {
                let info = res[0];
                callback(undefined, { code: 0, msg: "", data: info })
            }
        }).catch(err => {
            callback(undefined, { code: 500, msg: err, data: {} })
        })
    }
}

module.exports = Goods